package com.yf.exam.modules.trainingarchives.trainingclassinfo.service.impl;

import com.alibaba.druid.sql.visitor.functions.If;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.yf.exam.core.api.dto.BaseIdReqDTO;
import com.yf.exam.core.api.dto.PagingReqDTO;
import com.yf.exam.modules.trainingarchives.coursetemplate.entity.OrgCourseTemplate;
import com.yf.exam.modules.trainingarchives.coursetemplate.mapper.OrgCourseTemplateMapper;
import com.yf.exam.modules.trainingarchives.pdfexport.dto.second.TrainingClassInfoExportDTO;
import com.yf.exam.modules.trainingarchives.trainingclassinfo.dto.req.TrainingClassInfoReqDTO;
import com.yf.exam.modules.trainingarchives.trainingclassinfo.dto.resp.TrainingClassInfoRespDTO;
import com.yf.exam.modules.trainingarchives.trainingclassinfo.entity.TrainingClassInfo;
import com.yf.exam.modules.trainingarchives.trainingclassinfo.mapper.TrainingClassInfoMapper;
import com.yf.exam.modules.trainingarchives.trainingclassinfo.service.ITrainingClassInfoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yf.exam.modules.trainingarchives.trainingclassschedule.entity.TrainingClassSchedule;
import com.yf.exam.modules.trainingarchives.trainingclassschedule.mapper.TrainingClassScheduleMapper;
import com.yf.exam.modules.trainingarchives.trainingclassschedule.service.ITrainingClassScheduleService;
import com.yf.exam.modules.trainingarchives.worktype.mapper.OrgWorkTypeMapper;
import com.yf.exam.modules.user.UserUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 一期一档基础信息表 服务实现类
 * </p>
 *
 * @author author
 * @since 2024-12-29
 */
@Service
public class TrainingClassInfoServiceImpl extends ServiceImpl<TrainingClassInfoMapper, TrainingClassInfo> implements ITrainingClassInfoService {

    @Resource
    private OrgWorkTypeMapper orgWorkTypeMapper;

    @Resource
    private OrgCourseTemplateMapper orgCourseTemplateMapper;

    @Resource
    private ITrainingClassScheduleService trainingClassScheduleService;

    @Resource
    private TrainingClassScheduleMapper trainingClassScheduleMapper;


    /**
     * @param reqDTO
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean add(TrainingClassInfoReqDTO reqDTO) {
        TrainingClassInfo trainingClassInfo = new TrainingClassInfo();
        BeanUtils.copyProperties(reqDTO, trainingClassInfo);
        // 保存基础信息
        boolean save = this.save(trainingClassInfo);
        if (!save) {
            return false;
        }
        // 判断是不是初训 如果是初训根据工种id查询绑定的课程并插入课程安排表
        if (StringUtils.isNotBlank(reqDTO.getWorkTypeId()) && "初训".equals(reqDTO.getTrainingType())) {
            List<OrgCourseTemplate> orgCourseTemplates = orgCourseTemplateMapper.selectList(new LambdaQueryWrapper<OrgCourseTemplate>()
                    .eq(OrgCourseTemplate::getWorkTypeId, reqDTO.getWorkTypeId()));
            if (!CollectionUtils.isEmpty(orgCourseTemplates)) {
                List<TrainingClassSchedule> schedules = orgCourseTemplates.stream().map(item -> {
                    TrainingClassSchedule schedule = new TrainingClassSchedule();
                    schedule.setCourse(item.getCourse());
                    schedule.setHours(item.getHours());
                    schedule.setTrainingClassInfoId(trainingClassInfo.getId());
                    return schedule;
                }).collect(Collectors.toList());
                // 批量插入课程安排
                trainingClassScheduleService.saveBatch(schedules);
                //生成课程教师签到&教学计划执行基础信息
            }
        }
        return true;
    }

    /**
     * @param id
     * @return
     */
    @Override
    public Boolean deleteById(String id) {
        LambdaQueryWrapper<TrainingClassInfo> queryWrapper = Wrappers.lambdaQuery(TrainingClassInfo.class)
                .eq(TrainingClassInfo::getId, id);
        return this.remove(queryWrapper);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Boolean updateTrainingclasssInfO(TrainingClassInfoReqDTO reqDTO) {
        String trainingClassInfoId = reqDTO.getId();
        String trainingTypeReq = reqDTO.getTrainingType();
        TrainingClassInfo trainingClassInfo = new TrainingClassInfo();
        BeanUtils.copyProperties(reqDTO, trainingClassInfo);
        TrainingClassInfo trainingClassInfoResult = this.getById(trainingClassInfoId);
        String trainingType = trainingClassInfoResult.getTrainingType();
        if ("复训".equals(trainingTypeReq) && !trainingType.equals(trainingTypeReq)) {
            // 删除课程安排
            trainingClassScheduleMapper.delete(new LambdaQueryWrapper<TrainingClassSchedule>()
                .eq(TrainingClassSchedule::getTrainingClassInfoId, reqDTO.getId()));
        }
        if ("初训".equals(trainingTypeReq) && (!trainingType.equals(trainingTypeReq) || !reqDTO.getWorkTypeId().equals(trainingClassInfoResult.getWorkTypeId()))) {
            // 删除课程安排
            trainingClassScheduleMapper.delete(new LambdaQueryWrapper<TrainingClassSchedule>()
                    .eq(TrainingClassSchedule::getTrainingClassInfoId, reqDTO.getId()));
            List<OrgCourseTemplate> orgCourseTemplates = orgCourseTemplateMapper.selectList(new LambdaQueryWrapper<OrgCourseTemplate>()
                    .eq(OrgCourseTemplate::getWorkTypeId, reqDTO.getWorkTypeId()));
            if (!CollectionUtils.isEmpty(orgCourseTemplates)) {
                List<TrainingClassSchedule> schedules = orgCourseTemplates.stream().map(item -> {
                    TrainingClassSchedule schedule = new TrainingClassSchedule();
                    schedule.setCourse(item.getCourse());
                    schedule.setHours(item.getHours());
                    schedule.setTrainingClassInfoId(trainingClassInfo.getId());
                    return schedule;
                }).collect(Collectors.toList());
                // 批量插入课程安排
                trainingClassScheduleService.saveBatch(schedules);
            }
        }

        // 保存基础信息
        boolean save = this.updateById(trainingClassInfo);
        if (!save) {
            return false;
        }
        return true;
    }

    @Override
    public IPage<TrainingClassInfoRespDTO> paging(PagingReqDTO<TrainingClassInfoReqDTO> reqDTO) {
        String roles = UserUtils.getRoleIds();
        if (roles.contains("sa")) {
            return baseMapper.paging(reqDTO.toPage(), reqDTO.getParams());
        }
        reqDTO.getParams().setOrganizationId(UserUtils.getDepartId());
        return baseMapper.paging(reqDTO.toPage(), reqDTO.getParams());
    }

    @Override
    public TrainingClassInfoRespDTO getDetail(BaseIdReqDTO baseIdReqDTO) {
        TrainingClassInfo byId = this.getById(baseIdReqDTO.getId());
        TrainingClassInfoRespDTO trainingClassInfoRespDTO = new TrainingClassInfoRespDTO();
        BeanUtils.copyProperties(byId, trainingClassInfoRespDTO);
        return trainingClassInfoRespDTO;
    }

    /**
     * 获取安全培训计划表pdf数据
     *
     * @param trainingClassInfoId
     * @return
     */
    @Override
    public TrainingClassInfoExportDTO getPdfData(String trainingClassInfoId) {
        return baseMapper.getPdfData(trainingClassInfoId);
    }

}
